package com.xiaogao.sys.service.impl;

import com.xiaogao.common.utils.token.JwtUtils;
import com.xiaogao.common.utils.minio.MinioUtils;
import com.xiaogao.common.utils.tree.TreeUtils;
import com.xiaogao.sys.model.SysUser;
import com.xiaogao.sys.response.HomeResponse;
import com.xiaogao.sys.response.SysPermResponse;
import com.xiaogao.sys.service.*;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.lang.String;
import java.util.List;

@Service
@Slf4j
public class HomeServiceImpl implements HomeService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermService sysPermService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRolePermService sysRolePermService;
    @Autowired
    private MinioUtils minioUtils;

    @Override
    public HomeResponse home() {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parse(token);
        String realName = String.valueOf(claims.get("realName"));
        HomeResponse homeResponse = new HomeResponse();
        // 1、设置用户姓名
        homeResponse.setRealName(realName);

        String userId = String.valueOf(claims.get("userId"));
        SysUser loginUser = sysUserService.getById(userId);
        if(StringUtils.isNotEmpty(loginUser.getAvatar())){
            String fileUrl = minioUtils.getFileUrl(loginUser.getAvatar());
            homeResponse.setAvatar(fileUrl);
        }
        List<SysPermResponse> sysPermResponseList = sysPermService.queryByUserId(userId);
        if (!ObjectUtils.isEmpty(sysPermResponseList)) {
            // 2、查目录和菜单
            List<SysPermResponse> directoryAndMenus = sysPermResponseList.stream().filter(x -> !x.getType().equals("3")).toList();
            homeResponse.setMenuTree(TreeUtils.convertToTree(directoryAndMenus));
            // 3、查路由
            List<String> routers = sysPermResponseList.stream().filter(x -> x.getType().equals("2")).map(SysPermResponse::getPerm).toList();
            homeResponse.setRouters(routers);
            // 4、按钮权限
            List<String> buttons = sysPermResponseList.stream().filter(x -> x.getType().equals("3")).map(SysPermResponse::getPerm).toList();
            homeResponse.setButtons(buttons);
        }
        return homeResponse;
    }
}
